<script setup>
import { computed, nextTick, onMounted, ref, watch } from "vue"
import contextMenu from "@/component/contextMenu.vue";
import * as echarts from 'echarts';
import { deleteFile, createFile, getFileByParent, updateFile, getFAT } from "@/api/fileApi.js"
/** 
   * {
    "fileName": "test9",
    "path": "./src/main",
    "type": 2,
    "isDirectory": true,
    "fileContent": "你好你好这是test9"
     }
   * 
   */

const fileList = ref([])
const newFileForm = ref({
  fileName: "新文件",
  type: "READ_WRITE",
  isDirectory: true
})
const checkFileInfoTarget = ref({})
const newFileFormVisible = ref(false)
const checkFileInfoVisible = ref(false)
const pathList = ref(["."])
const openedFileList = ref([])
const curPath = computed(() => {
  return pathList.value.join("/") + "/"
})


// 磁盘信息状态
const diskUsageDialogVisible = ref(false);
const fatTable = ref([]);
const diskUsage = ref({ used: 0, free: 128 }); // 假设磁盘总共 128 块

// 计算磁盘占用情况
const totalBlocks = 128;

// 处理 “我的电脑” 按钮点击事件
async function openMyComputer() {
  diskUsageDialogVisible.value = true;
  await loadFAT();
  updateDiskUsageChart();
}

// 加载 FAT 数据
async function loadFAT() {
  const data = await getFAT();
  fatTable.value = data;
  console.log(data);
}

// 计算已用块数
const usedBlocks = computed(() => fatTable.value.length);

// 计算空闲块数
const freeBlocks = computed(() => totalBlocks - usedBlocks.value);

// 更新饼图数据
function updateDiskUsageChart() {
  const chartDom = document.getElementById('disk-usage-chart');
  const myChart = echarts.init(chartDom);
  const option = {
    title: {
      text: '磁盘使用情况',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '磁盘状态',
        type: 'pie',
        radius: '50%',
        data: [
          { value: usedBlocks.value, name: '已使用' },
          { value: freeBlocks.value, name: '空闲' },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  myChart.setOption(option);
}

// 每次打开对话框时，更新饼图数据
watch(diskUsageDialogVisible, (visible) => {
  if (visible) {
    nextTick(updateDiskUsageChart);
  }
});

watch(curPath, async (newPath) => {
  fileList.value = await getFileByParent(newPath)
})

function openNewFileForm() {
  newFileFormVisible.value = true
}

function handleMenuSelect(selectInfo) {
  const { data, label } = selectInfo
  const operation = fileOpsMap.get(label)
  operation && operation(data)
}

function HandleNewFileCancel() {
  newFileFormVisible.value = false
  newFileForm.value.fileName = "新文件"
  newFileForm.value.type = 1
  newFileForm.value.isDirectory = 1
}

function handlePathBack() {
  if (pathList.value.length > 1) {
    pathList.value.pop()
  }
}

function handlePathClick(path, index) {
  pathList.value = pathList.value.slice(0, index + 1)
}

async function onDeleteFile(id) {
  const res = await deleteFile(id)
  if (res === true) {
    console.log("ok", id)
  }
  fileList.value = await getFileByParent(curPath.value)
}

async function onCreateFile() {
  const newFile = {
    fileName: newFileForm.value.fileName,
    path: `${curPath.value}${newFileForm.value.fileName}`,
    type: newFileForm.value.type,
    isDirectory: newFileForm.value.isDirectory,
    fileContent: "",
    parent: `${curPath.value}`
  }
  console.log(newFile)
  const res = await createFile(newFile)
  newFileFormVisible.value = false
  fileList.value = await getFileByParent(curPath.value)
}

function onCheckFileInfo(id) {
  const target = fileList.value.find(file => {
    return id === file.fileId
  })
  checkFileInfoTarget.value = {
    ...target
  }
  checkFileInfoVisible.value = true
}

async function onOpenFile(id) {
  console.log("open", id)
  const targetFile = fileList.value.find(file => {
    return file.fileId === id
  })

  if (targetFile.isDirectory) {
    //打开的文件是文件夹时
    pathList.value.push(`${targetFile.fileName}`)
    fileList.value = await getFileByParent(curPath.value)
  } else {
    //打开文件
    if (openedFileList.value.findIndex(item => item.file === targetFile) < 0 && openedFileList.value.length < 5) {
      openedFileList.value.push({
        file: targetFile,
        visible: true
      })
    }

    // await nextTick(() => {
    //   const dialogModal = document.querySelector(".open-file-modal")
    //   dialogModal.setAttribute("style", "pointer-events:none")
    // })
  }
}

async function onCloseFile(id) {
  openedFileList.value = openedFileList.value.filter(item => {
    return item.file.fileId !== id
  })
  const file = fileList.value.find(file => file.fileId === id)
  updateFile(id, file)
}

async function handleUpdateFile(id, file) {
  if (openedFileList.value.findIndex(item => id === item.file.fileId) >= 0) {
    alert("文件已打开,不可修改属性信息")
    return
  }
  fileList.value[fileList.value.findIndex(file => file.fileId === id)] = file
  const res = await updateFile(id, file)
  if (res) {
    checkFileInfoVisible.value = false
  }
}

const fileMenu = [
  { label: "打开" },
  { label: "删除" },
  { label: "属性" },
]

const listMenu = [
  { label: "新建" }
]

const fileOpsMap = new Map()
fileOpsMap.set("删除", (data) => {
  const { fileId } = data
  onDeleteFile(fileId)
})
fileOpsMap.set("新建", () => {
  openNewFileForm()
})
fileOpsMap.set("打开", (data) => {
  const { fileId } = data
  onOpenFile(fileId)
})
fileOpsMap.set("属性", (data) => {
  const { fileId } = data
  onCheckFileInfo(fileId)
})


onMounted(async () => {
  fileList.value = await getFileByParent(curPath.value)
})

</script>

<template>
  <div class="App">
    <el-dialog v-model="newFileFormVisible" title="新建文件" width="500">
      <div class="new-file-form">
        <el-form :model="newFileForm" label-width="auto" style="max-width: 600px">
          <el-form-item label="文件名">
            <el-input v-model="newFileForm.fileName" />
          </el-form-item>
          <el-form-item label="读写权限">
            <el-radio-group v-model="newFileForm.type">
              <el-radio value="READ_ONLY">只读</el-radio>
              <el-radio value="READ_WRITE">可读可写</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="文件类型">
            <el-radio-group v-model="newFileForm.isDirectory">
              <el-radio :value="false">文件</el-radio>
              <el-radio :value="true">文件夹</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onCreateFile">新建</el-button>
            <el-button @click="HandleNewFileCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <div class="path">
      <img class="back-icon" src="@/static/back.png" @click="handlePathBack">
      <div class="path-item" v-for="(path, index) in pathList">
        <img v-if="index === 0" class="root-path-icon" src="@/static/file2.png" @click="handlePathClick(path, index)">
        <el-text v-else @click="handlePathClick(path, index)" :key="index">
          {{ path }}</el-text>
        <img src="@/static/arrow.png">
      </div>
    </div>
    <contextMenu :menu="listMenu" containerClass="file-list-container" @select="handleMenuSelect">
      <div class="file-list">
        <contextMenu containerClass="file-container" :menu="fileMenu" @on-close="" @select="handleMenuSelect"
          v-for="(file) in fileList" :key="file.fileId" :data="{ fileId: file.fileId }">
          <div class="file" @dblclick="onOpenFile(file.fileId)">
            <div v-if="!file.isDirectory" class="file-icon-wrapper">
              <img class="file-icon" src="@/static/file.png" style="object-fit: contain; width: 40px; height: 50px;">
            </div>
            <div v-if="file.isDirectory" class="directory-icon-wrapper">
              <img class="directory-icon" src="@/static/directory.png"
                style="object-fit: contain; width: 40px; height: 50px;">
            </div>
            <el-text>{{ file.fileName }}</el-text>
          </div>
        </contextMenu>
      </div>
      <div class="opened-file-list">
        <div class="opend-file" v-for="(item, i) in openedFileList" :key="item.file.fileId">
          <el-dialog v-model="item.visible" width="500" draggable overflow :modal="false"
            @closed="onCloseFile(item.file.fileId)" :close-on-click-modal="false" modal-class="open-file-modal">
            <template #header>
              <h3>打开：{{ item.file.fileName }}</h3>
            </template>
            <el-input style="outline: none;" :rows="10" v-model="item.file.fileContent"
              :disabled="item.file.type === `READ_ONLY`" type="textarea">
            </el-input>
          </el-dialog>
        </div>
      </div>
    </contextMenu>
    <el-dialog v-model="checkFileInfoVisible" title="文件属性信息" width="500">
      <div class="file-info">
        <el-form :model="checkFileInfoTarget" :disabled="checkFileInfoTarget.disabled" label-width="auto"
          style="max-width: 600px">
          <el-form-item label="文件名">
            <el-input v-model="checkFileInfoTarget.fileName" />
          </el-form-item>
          <el-form-item label="文件完整路径">
            <el-input disabled v-model="checkFileInfoTarget.path" />
          </el-form-item>
          <el-form-item label="读写权限">
            <el-radio-group v-model="checkFileInfoTarget.type">
              <el-radio value="READ_ONLY">只读</el-radio>
              <el-radio value="READ_WRITE">可读可写</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="文件类型">
            <el-radio-group v-model="checkFileInfoTarget.isDirectory">
              <el-radio :value="false">文件</el-radio>
              <el-radio :value="true">文件夹</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
              @click="handleUpdateFile(checkFileInfoTarget.fileId, checkFileInfoTarget)">保存</el-button>
            <el-button @click="() => { checkFileInfoVisible = false }">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <div>
      <el-button type="primary" @click="openMyComputer" style="float: right">存储空间</el-button>
    </div>

    <el-dialog v-model="diskUsageDialogVisible" title="磁盘使用情况" width="800">
      <div class="disk-usage-container">
        <!-- 左侧饼图 -->
        <div class="disk-usage-chart" id="disk-usage-chart" style="width: 350px; height: 300px;"></div>
        <!-- 右侧 FAT 表格 -->
        <div class="fat-table-container">
          <el-table :data="fatTable" style="width: 100%; table-layout: fixed;" height="300">
            <!-- 固定第一列显示0-127 -->
            <el-table-column label="Block ID" width="100">
              <template #default="{ $index }">
                {{ $index }}
              </template>
            </el-table-column>
            <!-- 第二列显示文件名 -->
            <el-table-column prop="file_name" label="文件名" width="150">
              <template #default="{ row }">
                <span>{{ row.fileName || '无文件名' }}</span>
              </template>
            </el-table-column>
            <!-- 第三列显示Next，默认值为0 -->
            <el-table-column label="Next" width="100">
              <template #default="{ row }">
                <span>{{ row.next || 0 }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

    </el-dialog>

  </div>
</template>

<style>
.open-file-modal {
  pointer-events: none;
}

.el-dialog {
  z-index: 2002;
  pointer-events: auto;
}
</style>

<style scoped>
.App {
  width: 80vw;
  height: 65vh;
  margin: auto;
  margin-top: 10vh;
  padding: 30px;
  outline: solid 2px #efefef;
  display: flex;
  flex-direction: column;

  .path {
    display: flex;
    border: solid 2px #efefef;

    .root-path-icon {
      transition: background-color 0.5s;
      &:hover {
        background-color: #a3cef7;
        outline: solid 1px #6bb6fc;
      }
    }

    .back-icon {
      transition: background-color 0.5s;

      &:hover {
        background-color: #a3cef7;
        outline: solid 1px #6bb6fc;
      }
    }

    .el-text {
      font-size: 18px;
      transition: all 0.3s;
      &:hover {
        color: #409EFF;
        text-decoration: underline;
      }
    }

    .path-item {
      cursor: pointer;
      display: flex;

    }
  }

  .file-list-container {
    display: flex;
    flex-grow: 1;

    .file-list {
      height: 100%;
      display: flex;
      flex-wrap: wrap;
      padding: 20px;

      .file-container {
        max-height: 120px;
        margin: 10px;

        .file {
          position: relative;
          display: flex;
          flex-direction: column;
          justify-self: center;
          padding: 20px;
          transition: background-color 0.5s;
          max-width: 80px;
          box-sizing: border-box;

          .el-text {
            max-width: 60px;
            word-break: break-all;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            text-shadow: 1px 1px 2px #9b9b9b;
            cursor: pointer;
          }
        }
      }

      .context-menu {
        position: fixed;
        width: 100px;
        height: 150px;
        outline: solid 1px #efefef;
        z-index: 1;
      }

      .file:hover,
      .file:active {
        background-color: #a3cef7;
        outline: solid 2px #6bb6fc;
      }

    }
  }
}

.disk-usage-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.disk-usage-chart {
  width: 45%;
}

.fat-table-container {
  width: 45%;
  overflow-x: auto;
  /* 防止表格溢出 */
}

.el-table {
  font-size: 14px;
  table-layout: fixed;
  /* 确保列宽固定 */
}
</style>
